package com.zengqingfa.examples.mybatisplus.strategy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.zengqingfa.examples.mybatisplus.entity.WarehouseProcess;
import com.zengqingfa.examples.mybatisplus.enums.ProcessTypeEnum;
import com.zengqingfa.examples.mybatisplus.mapper.WarehouseProcessGenMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 *
 * @fileName: ProcessStrategyFactory
 * @author: zengqf3
 * @date: 2021-4-8 17:24
 * @description:
 */
@Component
public class ProcessStrategyFactory implements InitializingBean {

    @Autowired
    List<ProcessStrategy> processStrategies;

    private static Map<ProcessTypeEnum, ProcessStrategy> processStrategyMap = Maps.newHashMap();
    ;

    @Autowired
    private WarehouseProcessGenMapper mapper;

    @Override
    public void afterPropertiesSet() {
        //进行初始化
        if (CollectionUtils.isNotEmpty(processStrategies)) {
            processStrategies.stream().forEach(p -> {
                processStrategyMap.put(p.getProcessTypeEnum(), p);
            });
        }
    }

    /**
     * 通过流程实例id获取策略
     * @param processId
     * @return
     */
    public ProcessStrategy getByProcessId(Long processId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(WarehouseProcess.PROCESS_ID, processId);
        WarehouseProcess warehouseProcess = mapper.selectOne(queryWrapper);
        if(warehouseProcess==null){
            return null;
        }
        ProcessTypeEnum anEnum = ProcessTypeEnum.getEnum(warehouseProcess.getProcessType());
        if (anEnum == null) {
            return null;
        }
        return processStrategyMap.get(anEnum);
    }
}
